<template>
  <!--  定价方法匹配规则模板 -->
  <div>
    <!-- 按钮与搜索 -->
    <el-row class="methodRule container">
      <el-col style="margin-right: 10px" class="content-left">
        <!-- 操作区域 -->
        <upper-template
          v-if="templateId"
          exportIcon
          importIcon
          :configIcon="false"
          @search="(searchForm.page = 1), searchFunc()"
          @clear="
            (searchForm.methodRuleCode = ''),
            (searchForm.effectDate = ''),
            (searchForm.invalidDate = '')
          "
        >
          <!-- 操作按钮区 -->
          <template slot="buttonArea" v-if="templateId">
            <el-button @click="addOrEditFunc('1')">新增</el-button>
            <el-button @click="addOrEditFunc('2')">编辑</el-button>
            <el-button @click="delFunc()">删除</el-button>
            <el-button @click="addOrEditFunc('3')">查看</el-button>
            <el-button @click="addOrEditFunc('4')">查看历史</el-button>
          </template>
          <div slot="exportArea">
                  <!-- 导出操作区域 -->
              <el-button @click="exportExcel('1')"
              >导出模板</el-button>
              <el-button @click="exportExcel('2')"
              >导出数据</el-button> 
         </div>
          <!-- 导入 -->
          <div slot="importArea">
                  <!-- 导入操作区域 -->
                  <el-upload
                    accept=".xls, .xlsx"
                    ref="upload"
                    :multiple="false"
                    :before-upload="beforeUpload"
                    :show-file-list="false"
                    action
                    :limit="1"
                    :http-request="uploadFile"
                  >
                    <el-button>导入</el-button>
                  </el-upload>
          </div>

          <!-- 搜索区 -->
          <template slot="searchArea">
            <el-form
              :model="searchForm"
              ref="searchForm"
              label-width="107px"
              label-position="left"
              size="mini"
            >
              <el-form-item label="编号：">
                <el-input
                  v-model="searchForm.methodRuleCode"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="生效日期：">
                <el-date-picker
                  v-model="searchForm.effectDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="截止日期：">
                <el-date-picker
                  v-model="searchForm.invalidDate"
                  value-format="yyyy-MM-dd"
                  type="date"
                  style="width: 150px"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </template>
        </upper-template>
        <!-- 列表 -->
        <el-table
          ref="multipleTable"
          :data="tableData"
          style="width: 100%"
          @row-click="authorizeFor"
          v-if="templateId"
        >
          <el-table-column
            width="55"
            type="selection"
            
          ></el-table-column>
          <el-table-column
            prop="methodRuleCode"
            label="规则编号"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            v-for="(value, key) in this.headData"
            :key="key"
            :prop="key"
            :label="value.elementFieldName"
            :formatter="getDynamicValue"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="ftpMethodId"
            label="定价方法"
            :show-overflow-tooltip="true"
            :formatter="formatFtpMethodId"
          ></el-table-column>
          <el-table-column
            prop="effectDate"
            :show-overflow-tooltip="true"
            label="生效日期"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.effectDate">
                {{ timeFormatShort(scope.row.effectDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="invalidDate"
            :show-overflow-tooltip="true"
            label="生效截止日"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.invalidDate">
                {{ timeFormatShort(scope.row.invalidDate) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="creator"
            label="创建人"
            :show-overflow-tooltip="true"
          ></el-table-column>
          <el-table-column
            prop="createdTm"
            :show-overflow-tooltip="true"
            label="创建时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.createdTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="modifier"
            :show-overflow-tooltip="true"
            label="修改人"
            sortable
            :formatter="(row) => row.modifier || '-'"
          >
          </el-table-column>
          <el-table-column
            prop="modifiedTm"
            :show-overflow-tooltip="true"
            label="修改时间"
            sortable
          >
            <template slot-scope="scope">
              <div v-if="scope.row.createdTm">
                {{ timeFormat(scope.row.modifiedTm) }}
              </div>
              <div v-else>-</div>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="templateId"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchForm.page"
          :page-size="searchForm.size"
          @refresh="searchFunc"
          :total="total"
        ></pagination>
      </el-col>
    </el-row>
    <!-- 新增、编辑弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="titleName"
      :visible.sync="methodRuleAddAndEditDi"
      width="45%"
      top="2%"
    >
      <el-form
        :model="saveRuleForm"
        ref="saveRuleForm"
        label-width="120px"
        label-position="right"
        :rules="saveRuleFormRules"
      >
        <el-row>
          <el-col :span="14">
            <el-form-item label="规则编号：" prop="methodRuleCode">
              <el-input
                v-model.trim="saveRuleForm.methodRuleCode"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              >（提示：只能输入字母、数字及下划线，最长字符数为40位）</el-form-item
            >
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="生效日期：" prop="effectDate">
              <el-date-picker
                v-model="saveRuleForm.effectDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="生效截止日：" prop="invalidDate">
              <el-date-picker
                v-model="saveRuleForm.invalidDate"
                value-format="yyyy-MM-dd"
                type="date"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="规则模板：">{{ ruleGroupName }}</el-form-item>
          </el-col>
        </el-row>
        <!-- 循环展示字段 -->
        <el-row v-for="(value, key) in this.headData" :key="key">
          <el-col :span="14">
            <dynamicForm :dataOriginProps="value" :key="key"></dynamicForm>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="14">
            <el-form-item label="定价方法：" prop="ftpMethodId">
              <el-select
                v-model="saveRuleForm.ftpMethodId"
                placeholder="请选择"
                style="width: 100%"
                @change="ftpMethodChange"
              >
                <el-option
                  v-for="item in ftpMethods"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="assignTypeDi">
          <el-col :span="14">
            <el-form-item label="指定类型：" prop="assignType">
              <el-select
                v-model="saveRuleForm.assignType"
                placeholder="请选择"
                style="width: 100%"
                @change="assignTypeChange"
              >
                <el-option
                  v-for="item in assignTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="assignTermDi">
          <el-col :span="14">
            <el-form-item label="指定期限：" prop="assignTermL">
              <el-col :span="14">
                <el-input
                  v-model="saveRuleForm.assignTermL"
                  maxlength="40"
                ></el-input>
              </el-col>
              <el-col :span="10">
                <el-select
                  v-model="saveRuleForm.assignTermR"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in assignTerms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="assignRateDi">
          <el-col :span="14">
            <el-form-item label="指定利率值(%)：" prop="assignRate">
              <el-input
                v-model.trim="saveRuleForm.assignRate"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="intDiffDi">
          <el-col :span="14">
            <el-form-item label="利差值：" prop="intDiff">
              <el-input
                v-model.trim="saveRuleForm.intDiff"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="trackDateTypeDi">
          <el-col :span="14">
            <el-form-item label="跟踪日期类型：" prop="trackDateType">
              <el-select
                v-model="saveRuleForm.trackDateType"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in trackDateTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="averagePeriodDi">
          <el-col :span="14">
            <el-form-item label="移动平均期限：" prop="averagePeriodL">
              <el-col :span="14">
                <el-input
                  v-model.trim="saveRuleForm.averagePeriodL"
                  maxlength="40"
                ></el-input>
              </el-col>
              <el-col :span="10">
                <el-select
                  v-model="saveRuleForm.averagePeriodR"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in assignTerms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="termTypeDi">
          <el-col :span="14">
            <el-form-item label="期限类型：" prop="termType">
              <el-select
                v-model="saveRuleForm.termType"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option label="原始期限" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="discountTypeDi">
          <el-col :span="14">
            <el-form-item label="折现率类型：" prop="discountType">
              <el-select
                v-model="saveRuleForm.discountType"
                placeholder="请选择"
                style="width: 100%"
                @change="discountTypeChange"
              >
                <el-option
                  v-for="item in discountTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="discountCurveIdDi">
          <el-col :span="14">
            <el-form-item label="折现曲线：" prop="discountCurveId">
              <el-select
                v-model="saveRuleForm.discountCurveId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in discountCurveIds"
                  :key="item.curveCode"
                  :label="item.curveName"
                  :value="item.curveCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="interestFlagDi">
          <el-col :span="14">
            <el-form-item label="是否含息：" prop="interestFlag">
              <el-select
                v-model="saveRuleForm.interestFlag"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in booleanFlags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="discountFlagDi">
          <el-col :span="14">
            <el-form-item label="是否折现：" prop="discountFlag">
              <el-select
                v-model="saveRuleForm.discountFlag"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in booleanFlags"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="balanceTableDi">
          <el-col :span="22">
            <el-form-item label="余额占比：">
              <el-row class="container">
                <el-col style="margin-right: 2px" class="content-left" >
                  <upper-template :searchIcon="false" :configIcon="false" >
                    <!-- 操作按钮区 -->
                    <template slot="buttonArea">
                      <el-button  size="mini" @click="addOrEditBananceTableFunc('1')"
                        >新增</el-button
                      >
                      <el-button  size="mini" @click="addOrEditBananceTableFunc('2')"
                        >编辑</el-button
                      >
                      <el-button  size="mini" @click="delBananceTableFunc()" >删除</el-button>
                    </template>
                  </upper-template>
                  
                  <el-table
                    ref="multipleBananceTable"
                    :data="saveRuleForm.repayCurves"
                    style="width: 100%"
                    @row-click="authorizeBananceTableFor" 
                  >
                    <el-table-column
                      width="55"
                      type="selection"
                      
                    ></el-table-column>
                    <el-table-column
                      prop="term"
                      label="期限"
                      :show-overflow-tooltip="true"
                      :formatter="datetimeFormatter"
                    ></el-table-column>
                    <el-table-column
                      prop="balanceRadio"
                      label="余额占比（%）"
                      :show-overflow-tooltip="true"
                    ></el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" v-if="ruleOperateType != '3'">
        <el-button @click="saveFunc">确 定</el-button>
        <el-button @click="methodRuleAddAndEditDi = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 新增、编辑弹窗 -->
    <!-- 余额占比弹窗 -->
    <el-dialog
      v-dialogDrag
      :title="bananceTableTitleName"
      :visible.sync="bananceTableAddAndEditDi"
      width="25%"
      top="2%"
    >
      <el-form
        :model="saveBananceTableForm"
        ref="saveOrEditBananceTableRef"
        label-width="120px"
        label-position="right"
        :rules="saveBananceTableFormRules"
      >
        <el-row>
          <el-col :span="18">
            <el-form-item label="期限：" prop="term">
              <el-col :span="10">
                <el-input
                  v-model.trim="saveBananceTableForm.termL"
                  maxlength="40"
                ></el-input>
              </el-col>
              <el-col :span="14">
                <el-select
                  v-model="saveBananceTableForm.termR"
                  placeholder="请选择"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in assignTerms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="余额占比：" prop="balanceRadio">
              <el-input
                v-model.trim="saveBananceTableForm.balanceRadio"
                maxlength="40"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="saveBananceTableFunc">确 定</el-button>
        <el-button @click="bananceTableAddAndEditDi = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 余额占比弹窗 -->
    <!-- 查看历史弹窗 -->
    <el-dialog
      v-dialogDrag
      title="历史信息查询页面"
      :visible.sync="historyVisible"
      width="60%"
      top="2%"
    >
      <historyTable
        :tableData="tableDataH"
        :headData="headDataH"
        :total="totalH"
        @handleSizeChange="handleSizeChangeH"
        @handleCurrentChange="handleCurrentChangeH"
        @searchFunc="getTableDataHistory"
      ></historyTable>
    </el-dialog>
    <!-- 查看历史弹窗 -->
  </div>
</template>

<script>
import { ruleTemplate,publicManage_pub } from "@/api/index";
import upperTemplate from "@/components/upperTemplate.vue";
import onlyOneSearch from "@/components/onlyOneSearch";
import { getDict } from "@/api/getDict";
import dynamicForm from "./components/dynamicForm";
import moment from "moment";
// 引入查看历史
import historyTable from "./components/historyTable";
export default {
  //定义数据
  data() {
    return {
      toFormData:[], // 回显的数据
      methodRuleId: "",
      searchForm: {
        page: 1,
        size: 15,
      },
      ruleOperateType: "",
      total: 0,
      titleName: "",
      methodRuleDi: false,
      headData: {},
      tableData: [],
      methodRuleAddAndEditDi: false,
      saveRuleForm: {
        repayCurves: [],
        ftpMethodId: "",
        effectDate: "",
        invalidDate: "",
        methodRuleId: "",
        methodRuleCode:"",
        ruleDatas: [],
        assignType: "",
        assignTermL: "",
        assignTermR: "",
        assignTerm:"",
        assignRate: "",
        intDiff: "",
        trackDateType: "",
        averagePeriodL: "",
        averagePeriodR: "",
        averagePeriod: "",
        termType: "",
        discountType: "",
        discountCurveId: "",
        interestFlag: "",
        discountFlag: ""
      },
      //定价方法数组
      ftpMethods: [],
      //表单字段规则校验
      saveRuleFormRules: {
        methodRuleCode: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9_]{1,40}$/,
            message: "只可输入(1-40)位的英文字母、数字和下划线！",
            trigger: "blur",
          },
        ],
        effectDate: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        invalidDate: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
          { validator: this.invalidDateFun, trigger: "blur" }
        ],
        ftpMethodId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        assignType: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        assignTermL: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        assignTermR: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        trackDateType: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        assignRate: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        interestFlag: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        discountFlag: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        intDiff: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        averagePeriod: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        averagePeriodL: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        averagePeriodR: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        balanceTable: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        discountCurveId: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
      },
      //指定类型标识
      assignTypeDi: false,
      //指定期限标识
      assignTermDi: false,
      //指定利率值标识
      assignRateDi: false,
      //利差值标识
      intDiffDi: false,
      //跟踪日期类型标识
      trackDateTypeDi: false,
      //移动平均期限
      averagePeriodDi: false,
      //期限类型
      termTypeDi: false,
      //折现率类型标识
      discountTypeDi: false,
      //折现曲线标识
      discountCurveIdDi: false,
      //是否含息标识
      interestFlagDi: false,
      //是否折现标识
      discountFlagDi: false,
      //余额占比标识
      balanceTableDi: false,
      //指定期限或利率值
      assignTypes: [],
      //指定期限数组
      assignTerms: [],
      //跟踪日期类型数组
      trackDateTypes: [],
      //折现率类型数组
      discountTypes: [],
      //折线曲线数组
      discountCurveIds: [],
      //是否数组
      booleanFlags: [],
      //列表标识
      rightListFlag: false,
      //待修改规则数据集合
      ruleDatas: [],
      //余额占比操作符
      bananceTableOperateType: "",
      //弹窗名
      bananceTableTitleName: "",
      //弹窗标识
      bananceTableAddAndEditDi: false,
      //保存表单
      saveBananceTableForm: {
        balanceRadio: "",
        termL: "",
        termR: "",
        term: ""
      },
      //原始数据
      saveBananceTableFormOld: {},
      //验证规则
      saveBananceTableFormRules: {
        term: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
        balanceRadio: [
          { required: true, message: "该输入项为必输项", trigger: "blur" },
        ],
      },
      //动态表单悬浮框
      elementFieldContent: false,
      //查询历史弹窗
      historyVisible: false,
      tableDataH: [],
      headDataH: {},
      rowHistory: {},
      pageH: 1,
      sizeH: 15,
      totalH: 0,
    };
  },
  props: {
    templateId: {
      type: String,
      default: "",
    },
    methodRuleGroup: {
      type: String,
      default: "",
    },
    ruleGroupName: {
      type: String,
      default: "",
    },
  },
  //组件引入
  components: {
    onlyOneSearch,
    dynamicForm,
    historyTable,
  },
  //创建初始化
  created() {
    this.ftpMethodsInit();
    this.assignTermsInit();
  },
  mounted() {},
  //监控数值变化
  watch: {
    templateId: function (newVal, oldVal) {
      this.templateId = newVal;
      this.searchForm.page = 1;
      this.searchForm.size = 15
    },
    methodRuleGroup: function (newVal, oldVal) {
      this.methodRuleGroup = newVal;
    },
    ruleGroupName: function (newVal, oldVal) {
      this.ruleGroupName = newVal;
    },
  },
  //运算
  computed: {},
  methods: {
    //格式化
    datetimeFormatter(rows, column) {
      let str = "";
      switch (this.getTimeTypeQueen(rows.term)) {
        case "Y":
          str = this.getTimeTypeFront(rows.term) + "年";
          break;
        case "M":
          str = this.getTimeTypeFront(rows.term) + "月";
          break;
        case "D":
          str = this.getTimeTypeFront(rows.term) + "天";
          break;
        default:
          break;
      }
      return str;
    },
     getTimeTypeQueen(val) {
      return val.slice(-1);
    },
      getTimeTypeFront(val) {
      return val.slice(0, -1);
    },
    //余额占比新增、修改弹窗
    addOrEditBananceTableFunc(val) {
      this.bananceTableOperateType = val;
      if (this.bananceTableOperateType == "1") {
        this.bananceTableTitleName = "新增偿还曲线法余额占比信息";
        this.saveBananceTableForm.termL = "",
        this.saveBananceTableForm.termR = "",
        this.saveBananceTableForm.balanceRadio = ""
        this.bananceTableAddAndEditDi = true;
        //清除校验结果
        this.$nextTick(()=>{
         this.$refs.saveOrEditBananceTableRef.clearValidate();
        })
        
      } else if (this.bananceTableOperateType == "2") {
        let selection = this.$refs.multipleBananceTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          this.bananceTableTitleName = "编辑偿还曲线法余额占比信息";
          this.bananceTableAddAndEditDi = true;
          this.saveBananceTableForm = Object.assign({}, this.saveBananceTableForm,selection[0])
          this.saveBananceTableFormOld = selection[0];
          this.saveBananceTableForm.termL = selection[0].term.substr(
            0,
            selection[0].term.length - 1
          );
          this.saveBananceTableForm.termR = selection[0].term.substr(
            selection[0].term.length - 1,
            1
          );
        }
      }
    },
    //保存余额占比
    saveBananceTableFunc() {
        this.saveBananceTableForm.term =
        this.saveBananceTableForm.termL + this.saveBananceTableForm.termR;
       this.$refs["saveOrEditBananceTableRef"].validate((valid) => {
        if (valid) {
      let data = { ...this.saveBananceTableForm };
      if (this.bananceTableOperateType == "1") {
        this.saveRuleForm.repayCurves.push(data);
        this.bananceTableAddAndEditDi = false;
      } else if (this.bananceTableOperateType == "2") {
        this.saveRuleForm.repayCurves.splice(
          this.saveRuleForm.repayCurves.indexOf(this.saveBananceTableFormOld),
          1,
          data
        );
        this.bananceTableAddAndEditDi = false;
      }  
        }
      });
    },
    //删除余额占比
    delBananceTableFunc() {
      let selection = this.$refs.multipleBananceTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的余额占比数据");
      }
      selection.forEach((item) => {
        this.saveRuleForm.repayCurves.splice(
          this.saveRuleForm.repayCurves.indexOf(item),
          1
        );
      });
    },
    // 删除
    delFunc() {
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("您确定要删除选中数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let data = { ids: selection.map((v) => v.methodRuleId) };
          ruleTemplate.methodRuleRemove(data).then((res) => {
            if (res.code == 200) {
              this.$message.success("删除成功");
              this.searchFunc();
            } else {
              this.$message.error(res.message || "删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //校验余额占比
    checkRate() {
      let totalSumAll = 0;
     var args = this.saveRuleForm.repayCurves, // 获取所有参数
      lens = args.length, // 获取参数的长度
      d = 0, // 定义小数位的初始长度，默认为整数，即小数位为0
      sum = 0 
      for(var key in args){
        var str = ""+args[key].balanceRadio;
        if(str.indexOf(".")!= -1){
          // 获取小数长度
          var temp = str.split(".")[1].length;
          // 比较此数的小数位与原小数位的长度，取小数位较长的存储到d中
          d = d < temp ? temp:d
        }
      }
      // 计算需要乘的数值
      var m = Math.pow(10,d);
      for(var key in args){
         if (!isNaN(args[key].balanceRadio)){
           sum += args[key].balanceRadio*m
         } 
      }
      return sum/m;
  },
    //保存
    saveFunc() {
      this.$refs["saveRuleForm"].validate((valid) => {
        if (valid) {
      //余额占比的校验
      if(this.balanceTableDi){
        console.log(this.saveRuleForm.repayCurves)
        if(this.saveRuleForm.repayCurves.length < 2) {
          this.$message.warning("至少输入两条以上的余额占比信息")
          return
        }
        // 校验余额占比
        if(this.checkRate() != 100){
           this.$message.warning("占比不为100%,请修改")
           return
        }
      }
        let ruleDatas = [];
        for (var keyHeadData in this.headData) {
          let map = {
            templateFieldId: keyHeadData,
            ruleValue: this.headData[keyHeadData][keyHeadData],
          };
          ruleDatas.push(map);
        }
        this.saveRuleForm.ruleDatas = ruleDatas;
        this.saveRuleForm.templateId = this.templateId;
        this.saveRuleForm.methodRuleGroup = {
          methodRuleGroup: this.methodRuleGroup,
          ruleGroupName: this.ruleGroupName,
        };
      //部分字段拆分成两部分的数据合并
      this.dataMerge()
      let data = {
        operateType: this.ruleOperateType,
        methodRule: { ...this.saveRuleForm },
      };
      ruleTemplate.methodRuleSave(data).then((res) => {
        if (res.code === 200) {
          this.methodRuleAddAndEditDi = false;
          this.$message.success("保存成功");
          this.searchFunc();
        } else {
          this.$message.error(res.message || "保存失败");
        }
      });   
        } else {
          this.$message.warning("请填写正确的信息！");
        }
      });
    },
    //新增、编辑弹窗
    addOrEditFunc(val) {
      this.ruleOperateType = val;
      // 调用toForm回显接口
      this.getMethodRuleToForm()
      if (this.ruleOperateType === "1") {
        this.hiddenEleInit()
        if (this.templateId == "") {
          this.$message.warning("请在左侧选择模板");
          return;
        }
        this.titleName = "新增定价方法匹配规则信息";
        this.methodRuleAddAndEditDi = true;
        this.$nextTick(() => {
        //清除校验结果
        this.$refs.saveRuleForm.clearValidate();
      });
        //清空表单
        this.emptydataTableForm();
        this.emptyDynamicMethod()
      } else if (this.ruleOperateType === "2" || this.ruleOperateType === "3" ) {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          this.titleName = this.ruleOperateType == '2'? "编辑定价方法匹配规则信息":"查看定价方法匹配规则信息";
          this.methodRuleAddAndEditDi = true;
          // 清除不必要的保存数据
          for (let keyHeadData in this.headData) {
              delete this.saveRuleForm[keyHeadData]
          }
          //回写定价方法选择字段
          this.ftpMethodChange(selection[0].ftpMethodId);
          //回写指定类型
          this.assignTypeChange(selection[0].assignType);
          //回写折现率类型
          this.discountTypeChange(selection[0].discountType)
          this.saveRuleForm = Object.assign({},this.saveRuleForm,selection[0]) 
          this.dataSplit(this.saveRuleForm);
        }
      } else if (this.ruleOperateType === "4") {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length < 1) {
          return this.$message.warning("请选择一条数据");
        } else if (selection.length > 1) {
          return this.$message.warning("只能选择一条数据");
        } else {
          //查看历史页面
          this.historyVisible = true;
          this.rowHistory = selection[0];
          // 获取历史页面数据
          this.getTableDataHistory();
        }
      }
    },
    // 获取回显数据
    getMethodRuleToForm() {
      this.methodRuleId = ""
      let selection = this.$refs.multipleTable.selection;
      //新增
      if(this.ruleOperateType == '2' || this.ruleOperateType == '3'){
        if(selection.length !="1"){
          this.$message.warning("请选择一条数据")
          return
        }
       this.methodRuleId = selection[0].methodRuleId
      }
      let params = {
        methodRuleId: this.methodRuleId,
        templateId: this.templateId
      }
      ruleTemplate
        .methodRuleToForm(params)
        .then((res) => {
          if (res.code === 200) {
            this.toFormData = res.datas[0]
            for(let i = 0;i<this.toFormData.length;i++){
              for(let val in this.headData){
                if(this.toFormData[i].key == val){
                  this.$set(this.headData[val],this.headData[val].templateFieldId,this.toFormData[i].value)
                  this.$set(this.headData[val],this.headData[val].templateFieldIdName,this.toFormData[i].valueName)
                }
              }
            }
            
          }
        });
    },
    emptydataTableForm() {
      this.saveRuleForm.ftpMethodId = "";
      this.saveRuleForm.effectDate = "";
      this.saveRuleForm.invalidDate = "";
      this.saveRuleForm.methodRuleId = "";
      this.saveRuleForm.methodRuleCode = "";
      this.saveRuleForm.ruleDatas = [];
    },
    //清空动态方法表单
    emptyDynamicMethod() {
      this.saveRuleForm.intDiff = ""; //利率差值
      this.saveRuleForm.assignType = ""; //指定类型
      this.saveRuleForm.trackDateType = ""; //跟踪日期类型
      this.saveRuleForm.assignRate = ""; // //指定利率值
      this.saveRuleForm.interestFlag = ""; // 是否含息
      this.saveRuleForm.discountFlag = ""; // 是否折现
      this.saveRuleForm.assignTerm = ""; //指定期限
      this.saveRuleForm.assignTermL = ""; //指定期限
      this.saveRuleForm.assignTermR = ""; //指定期限
      this.saveRuleForm.averagePeriod = ""; //移动平均期限
      this.saveRuleForm.averagePeriodL = ""; //移动平均期限
      this.saveRuleForm.averagePeriodR = ""; //移动平均期限
      this.saveRuleForm.repayCurves = []; //偿还曲线法
      this.saveRuleForm.termType = ""; //期限类型
      this.saveRuleForm.discountType = ""; //折现率类型
      this.saveRuleForm.discountCurveId = ""; ////折现曲线
    },
    getTableDataHistory() {
      let params = {
        methodRuleCode: this.rowHistory.methodRuleCode,
        page: this.pageH,
        ruleStatus: '0',
        size: this.sizeH,
        templateId: this.rowHistory.templateId,
      };
      ruleTemplate.findHistory(params).then((res) => {
        if (res.code == 200) {
          this.headDataH = res.datas.fieldsAndTitles;
          this.tableDataH = res.datas.rows;
          this.totalH = res.datas.total;
        } else {
          this.$message.warning(res.message);
        }
      });
    },
    //定价方法数组初始化
    ftpMethodsInit() {
      getDict("ftp_cp_ftp_method").then((res) => {
        if (res.code == 200) {
          this.ftpMethods = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    formatFtpMethodId(row){
      return this.$getLabel(row.ftpMethodId, this.ftpMethods);
    },
    //指定期限或利率值初始化
    assignTypesInit() {
      getDict("ftp_cp_assign_type_cd").then((res) => {
        if (res.code == 200) {
          this.assignTypes = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //指定期限数组初始化
    assignTermsInit() {
      getDict("ftp_cp_time_type").then((res) => {
        if (res.code == 200) {
          this.assignTerms = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //跟踪日期类型数组初始化
    trackDateTypesInit() {
      getDict("ftp_cp_track_date_cd").then((res) => {
        if (res.code == 200) {
          this.trackDateTypes = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //折现率类型数组初始化
    discountTypesInit() {
      getDict("ftp_discountType").then((res) => {
        if (res.code == 200) {
          this.discountTypes = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //折线曲线数组初始化
    discountCurveIdsInit() {
      // 查询曲线
      publicManage_pub.baseCurveDefQuery({ page: 1, size: 999 }).then(res => {
        if (res.code == 200) {
          this.discountCurveIds = res.data;
        }
      });
    },
    //是否数组初始化
    booleanFlagsInit() {
      getDict("ftp_boolean_flag").then((res) => {
        if (res.code == 200) {
          this.booleanFlags = res.datas;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    //获取字典数据
    getDictData(val) {
      ruleTemplate.methodRuleFindAll({ templateFieldId: val }).then((res) => {
        if (res.code === 200) {
          let result = res.datas;
          getDict(result.data).then((res) => {
            if (res.code == 200) {
              return res.datas;
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    //   点击行选中
    authorizeFor(row) {
      if (this.$refs.multipleTable) {
        this.$refs.multipleTable.clearSelection();
      }
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    //余额占比点击行选中
    authorizeBananceTableFor(row) {
      if (this.$refs.multipleBananceTable) {
        this.$refs.multipleBananceTable.clearSelection();
      }
      this.$refs.multipleBananceTable.toggleRowSelection(row, true);
    },
    //查询数据
    searchFunc() {
      this.rightListFlag = true;
      this.searchForm.templateId = this.templateId;
      this.searchForm.methodRuleGroup = this.methodRuleGroup;
      console.log(this.searchForm.templateId,"---this.searchForm.templateId");
      console.log(this.searchForm.methodRuleGroup,"---this.searchForm.methodRuleGroup");
      ruleTemplate
        .findFieldListByTemplateId({ templateId: this.templateId })
        .then((res) => {
          if (res.code === 200) {
            this.headData = res.datas.fieldValues;
          }
          ruleTemplate.methodRuleFindAll(this.searchForm).then((res) => {
            if (res.code == 200) {
              this.tableData = res.datas.rows;
              this.total = res.datas.total;
            }
          });
        });
    },

    //定价方法变化
    /**
     *根据定价方法显示元素
     * 1	指定利率法
     * 2	期限匹配法
     * 3	现金流法
     * 4	利率差额法
     * 5	移动平均法
     * 6	偿还曲线法
     * 7	久期法
     * 8 结构化
     */
    ftpMethodChange(val) {
      this.hiddenEleInit();
      if (val == "1") {
        this.assignTypeDi = true;
        this.assignTypesInit();

      } else if (val == "3") {
        this.interestFlagDi = true;
        this.discountFlagDi = true;
        this.booleanFlagsInit();
      } else if (val == "4") {
        this.intDiffDi = true;
      } else if (val == "5") {
        this.assignTermDi = true;
        this.averagePeriodDi = true;
      } else if (val == "6") {
        this.balanceTableDi = true;
      } else if (val == "7") {
        this.termTypeDi = true;
        this.discountTypeDi = true;
        this.discountTypesInit();
      }
    },
    //指定类型变化
    assignTypeChange(val) {
      if (val == "0") {
        this.assignRateDi = false;
        this.saveRuleForm.assignRate =""
        this.assignTermDi = true;
        this.trackDateTypeDi = true;
        this.trackDateTypesInit();
      } else if (val == "1") {
        this.assignTermDi = false;
        this.saveRuleForm.assignTerm =""
        this.saveRuleForm.assignTermL =""
        this.saveRuleForm.assignTermR=""
        this.trackDateTypeDi = false;
        this.saveRuleForm.trackDateType=""
        this.assignRateDi = true;
      }
    },
    //页面初始化隐藏元素
    hiddenEleInit() {
      //指定类型标识
      this.assignTypeDi = false;
      //指定期限标识
      this.assignTermDi = false;
      //指定利率值标识
      this.assignRateDi = false;
      //利差值标识
      this.intDiffDi = false;
      //跟踪日期类型标识
      this.trackDateTypeDi = false;
      //移动平均期限
      this.averagePeriodDi = false;
      //期限类型
      this.termTypeDi = false;
      //折现率类型标识
      this.discountTypeDi = false;
      //折现曲线标识
      this.discountCurveIdDi = false;
      //是否含息标识
      this.interestFlagDi = false;
      //是否折现标识
      this.discountFlagDi = false;
      //余额占比标识
      this.balanceTableDi = false;
      //清空动态方法表单
      this.emptyDynamicMethod()
    },
    //折现率类型变化
    discountTypeChange(val) {
      if (val == "1") {
        this.discountCurveIdDi = false;
        this.saveRuleForm.discountCurveId =""
      } else if (val == "2") {
        this.discountCurveIdDi = true;
        this.discountCurveIdsInit();
      }
    },
    //列表动态数据赋值
    getDynamicValue(row, column) {
      let columnId = column.property;
      let data = row.ruleDatas;
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].templateFieldId == columnId) {
            return row[columnId];
          }
        }
      }
    },
    //部分字段拆分成两部分的数据合并
    dataMerge() {
      if (
        this.saveRuleForm.assignTermL != "" &&
        this.saveRuleForm.assignTermR != ""
      ) {
        this.saveRuleForm.assignTerm =
          this.saveRuleForm.assignTermL + this.saveRuleForm.assignTermR;
      }
      if (
        this.saveRuleForm.averagePeriodL != "" &&
        this.saveRuleForm.averagePeriodR != ""
      ) {
        this.saveRuleForm.averagePeriod =
          this.saveRuleForm.averagePeriodL + this.saveRuleForm.averagePeriodR;
      }
    },
    //部分字段拆分成两部分
    dataSplit() {
      if (this.saveRuleForm.assignTerm != "" && this.saveRuleForm.assignTerm != undefined && this.saveRuleForm.assignTerm === this.saveRuleForm.assignTerm ) {
        this.saveRuleForm.assignTermL = this.saveRuleForm.assignTerm.substr(
          0,
          this.saveRuleForm.assignTerm.length - 1
        );
        this.saveRuleForm.assignTermR = this.saveRuleForm.assignTerm.substr(
          this.saveRuleForm.assignTerm.length - 1,
          1
        );
      }
      if (this.saveRuleForm.averagePeriod != "" && this.saveRuleForm.averagePeriod != undefined &&  this.saveRuleForm.averagePeriod === this.saveRuleForm.averagePeriod) {
        this.saveRuleForm.averagePeriodL = this.saveRuleForm.averagePeriod.substr(
          0,
          this.saveRuleForm.averagePeriod.length - 1
        );
        this.saveRuleForm.averagePeriodR = this.saveRuleForm.averagePeriod.substr(
          this.saveRuleForm.averagePeriod.length - 1,
          1
        );
      }
    },
    //事件转换
     timeFormat(val) {
      if (val) return moment(val).format("YYYY-MM-DD HH:mm:ss");
      else return "";
    },
    timeFormatShort(val) {
      if (val) return moment(val).format("YYYY-MM-DD");
      else return "";
    },
    //页码值改变
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.searchForm.size = val;
      this.searchFunc();
    },
    //当前页改变
    handleCurrentChange(val) {
      this.searchForm.page = val;
      console.log(`当前页: ${val}`);
      this.searchFunc();
    },
    //页码值改变
    handleSizeChangeH(val) {
      this.sizeH = val;
      this.getTableDataHistory();
    },
    //当前页改变
    handleCurrentChangeH(val) {
      this.pageH = val;
      console.log(`当前页: ${val}`);
      this.getTableDataHistory();
    },
    invalidDateFun(rule, value, callback){
    	var effectDate = this.saveRuleForm.effectDate;
      var date1 = new Date(Date.parse(effectDate.replace("-","/")));
      var date2 = new Date(Date.parse(value.replace("-","/")));
		
        if (date1 > date2) {
        	return callback(new Error("生效截止日必须大于等于生效日期!"));
        }else callback();
    },
    //导出文件
    exportExcel(tmpFlag) {

      //校验：
      if(this.templateId==''){
        this.$message.success("请先选择一条数据，再进行点击下载!");
      } else {
        let selection = this.$refs.multipleTable.selection;

        let param = {
          hasTemplete: tmpFlag, //1为导出模板
          methodRuleCode: this.searchForm.methodRuleCode,  
          effectDate: this.searchForm.effectDate,
          invalidDate: this.searchForm.invalidDate,
          templateId: this.templateId,
          methodRuleGroup: this.methodRuleGroup,
          selectedData: selection.map((v) => v.methodRuleId)
        };

        console.log(param,"---param");

        ruleTemplate
        .expMethodRule(param)
        .then((res) => {
          if (res) {
            var filename = decodeURI(res.headers["content-disposition"]).split("=")[1];
            let contenttype =
              filename.substring(filename.lastIndexOf("."), filename.length) === "xlsx"
                ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"
                : "application/vnd.ms-excel;charset=utf-8";
            const content = res.data;
            const blob = new Blob([content], {
              type: contenttype,
            });
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement("a");
            link.style.display = "none";
            link.href = url;
            link.setAttribute("download", filename);
            document.body.appendChild(link);
            link.click();
          }
        })
        .catch(function (error) {
          console.log(error);
          // this.$message.error("导出失败！");
        });

      }
    },
     // 上传文件之前的钩子
    beforeUpload(file) {
      let name = file.name;
      let type = name.substring(name.lastIndexOf("."), name.length);
      if (type === ".xls" || type === ".xlsx") {
        return true;
      } else {
        this.$message.warning("只能选择xls或者xlsx格式的文件上传");
        return false;
      }
    },
     // 上传文件
    uploadFile(item) {
      let form = new FormData();
      // 文件对象
      form.append("excelFile", item.file);
      // 发送请求
      ruleTemplate.impMethodRule(form)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success("导入成功");
            this.searchFunc();
          } else {
            this.$message.error(res.message);
          }
          this.$refs.upload.clearFiles();
        })
        .catch((err) => {
          this.$refs.upload.clearFiles();
        });
    },







  },
};
</script>


<style lang="scss" scoped>
.buessinessEleTable .el-table__header th {
  /deep/ .cell {
    white-space: nowrap !important;
  }
}

/deep/.el-dialog__body {
  max-height: 400px;
}
.tipMessage {
  line-height: 32px;
  margin-left: 5px;
  color: red;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500 !important;
  font-size: 12px !important;
}
.selectBox {
  background: url("~@/assets/images/select_btn.gif");
  background-repeat: no-repeat;
  height: 26px;
  width: 23px;
  position: absolute;
  right: 0;
  top: 5px;
  cursor: pointer;
}
/deep/.el-popover {
  max-height: 160px;
  overflow: auto;
}
</style>

